let registration: any = null;

export interface emitEventType {
  type: 'update' | 'refresh';
  data: any;
}
export const registerServiceWorker = async (callback: (e: emitEventType) => void) => {
    if ('serviceWorker' in navigator) {
        try {
            registration = await navigator.serviceWorker.register('./sw.js');
            setInterval(() => {
                console.log('665+')
                registration.update(); // 强制检查更新
            }, 5000);
            if (navigator.serviceWorker.controller) {
                console.log('Service Worker 已激活');
            }
            registration.addEventListener('updatefound', () => {
                console.log('发现新版本updatefound');
                const newWorker = registration?.installing;
                if (newWorker) {
                    newWorker.addEventListener('statechange', () => {
                        if (newWorker.state === 'activated' && navigator.serviceWorker.controller) {
                            callback && callback({ type: 'update', data: true });
                        }
                    });
                }
            });
            // 监听控制器变化
            navigator.serviceWorker.addEventListener('controllerchange', () => {
                console.log('Service Worker 控制器已变更');
            });
        } catch (error) {
            console.error('Service Worker 注册失败:', error);
        }
    }
};

// 打印所有缓存
export async function printCachedRequests() {
    const cacheNames = await caches.keys(); // 获取所有缓存的名称
    for (const cacheName of cacheNames) {
        const cache = await caches.open(cacheName); // 打开缓存
        const requests = await cache.keys(); // 获取所有请求
        console.log(`📂 缓存名称: ${cacheName}`, cache);
        requests.forEach(request => console.log(`✅ 缓存请求: ${request.url}`));
    }
}
printCachedRequests()
// 发送消息给 Service Worker
export const sendMessage = async (message: string) => {
    if (navigator.serviceWorker.controller) {
        navigator.serviceWorker.controller.postMessage(message);
    }
};
// 接收 Service Worker 的消息
const listenToMessages = () => {
    navigator.serviceWorker.addEventListener('message', (event) => {
        console.log('sw的message', event)
    });
};